package com.zhkj.crawl.rank.ext;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverLogLevel;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

@Slf4j
public class ChromeAliExt {
    private static final boolean isWindows = System.getProperty("os.name").toLowerCase().contains("win");

    public static void main(String[] args) {
        enter();

    }

    private static void enter(){
        ChromeDriver driver = initDriver();
        try {
            String loginUrl = "https://www.ip.cn/api/index?ip=&type=0";
//            String loginUrl = "https://login.aliexpress.com/?returnUrl=https%3A%2F%2Ftrade.aliexpress.com%2ForderList.htm";
//            String loginUrl = "https://www.aliexpress.com/";
            toPage(driver, loginUrl);

//            optLogin(driver);
        }finally {
            //driver.quit();
        }

    }

    private static void optLogin(ChromeDriver driver) {
//        // 去除遮罩
//        WebElement cover = driver.findElementByClassName("poplayer-content");
//        if(cover != null && cover.isDisplayed()){
//            cover.findElement(By.className("btn-close")).click();
//        }
//
//        // 点击登陆出现登陆窗口
//        WebElement hoverTar = driver.findElementById("nav-user-account");
//        Actions actions = new Actions(driver);
//        actions.moveToElement(hoverTar).perform();
//        driver.findElementByClassName("sign-btn").click();
//        handleYzm(driver);
//
//        sleep(2);
        // 填写账密
        WebElement username = driver.findElementById("fm-login-id");
        WebElement password = driver.findElementById("fm-login-password");

        username.sendKeys("930998306@qq.com");
        password.sendKeys("123654");

        //driver.getKeyboard().sendKeys(Keys.F12);
        driver.getKeyboard().sendKeys(Keys.chord(Keys.CONTROL, Keys.SHIFT, "i"));
        sleep(1);
        handleYzm(driver);


        // 被风控 关闭F12 刷新重来
        if(blocked(driver)){

        }

        WebElement submit = driver.findElementByClassName("login-submit");
        submit.click();


    }

    private static boolean blocked(ChromeDriver driver) {
        try {
            WebElement blockText = driver.findElementByClassName("nc-lang-cnt");
            return blockText.isDisplayed() && StringUtils.isNotBlank(blockText.getText());
        }catch (Exception e){}
        return false;
    }

    private static boolean handleYzm(ChromeDriver driver){
        WebElement yzm = null;
        WebDriver frame = null;
        try {
            frame = driver.switchTo().frame("baxia-dialog-content");
            yzm = frame.findElement(By.id("nc_1__scale_text"));
            System.out.println("处理验证码");
        }catch (Exception ignored){}


        if (frame != null && yzm != null && yzm.isDisplayed()) {
            //滑块控件元素
            WebElement nc_1_n1z = frame.findElement(By.id("nc_1_n1z"));
            int cw = nc_1_n1z.getSize().getWidth();
            //整个拖拽框的控件元素
            WebElement nc_1__scale_text = frame.findElement(By.id("nc_1__scale_text"));
            int x = nc_1__scale_text.getSize().getWidth();
            int y = nc_1__scale_text.getSize().getHeight();

            WebElement target = frame.findElement(By.id("nc_1_wrapper"));

            Actions actions = new Actions(frame);
            actions.dragAndDropBy(target, x, y).perform();

            System.out.println("处理验证码 done");
            sleep(2);
            screenshot(driver);

            return true;
        }
        return false;
    }

    private static void toPage(ChromeDriver driver, String url){
        driver.get(url);
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    }

    private static ChromeDriver initDriver() {
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.setLogLevel(ChromeDriverLogLevel.OFF);
        if(!isWindows){
            chromeOptions.addArguments("-headless");
        }
        chromeOptions.addArguments("--silent");
        chromeOptions.addArguments("log-level=3");
        chromeOptions.addArguments("--disable-blink-features=AutomationControlled");
        chromeOptions.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));

        ChromeDriver chromeDriver = new ChromeDriver(chromeOptions);
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("source", " Object.defineProperty(navigator, 'webdriver', {\n" +
                "      get: () => undefined\n" +
                "    })");
        chromeDriver.executeCdpCommand("Page.addScriptToEvaluateOnNewDocument", parameters);

        return chromeDriver;
    }


    private static void sleep(Integer second){
        try {
            TimeUnit.SECONDS.sleep(second);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void screenshot(ChromeDriver driver) {
        //调用截图方法 ,指定了OutputType.FILE做为参数传递给getScreenshotAs()方法，其含义是将截取的屏幕以文件形式返回
        File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

        String name = "selenium-" + RandomStringUtils.randomAlphanumeric(6) + ".jpg";
        try {
            FileUtils.copyFile(srcFile, new File("D:\\" + name + ""));
        } catch (IOException e) {
            log.error("截图错误", e);
        }
    }


    static {
        Logger.getLogger("org.openqa.selenium").setLevel(Level.OFF);
        System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
        if (isWindows) {
            System.setProperty("webdriver.chrome.driver", "D:\\Program Files\\chromedriver_91_0_4472_101.exe");
        }
    }
}
